#include "PhaCompare.h"

#include <opencv2/opencv.hpp>

double PhaCompare::matCompare(std::string matSrcPath, std::string matDstPath)
{
	cv::Mat matSrc, matSrc1, matSrc2;

	matSrc = cv::imread(matSrcPath);
	CV_Assert(matSrc.channels() == 3);

	cv::resize(matSrc, matSrc1, cv::Size(357, 419), 0, 0, cv::INTER_NEAREST);
	//cv::flip(matSrc1, matSrc1, 1);
	cv::resize(matSrc, matSrc2, cv::Size(2177, 3233), 0, 0, cv::INTER_LANCZOS4);

	cv::Mat matDst1, matDst2;

	cv::resize(matSrc1, matDst1, cv::Size(8, 8), 0, 0, cv::INTER_CUBIC);
	cv::resize(matSrc2, matDst2, cv::Size(8, 8), 0, 0, cv::INTER_CUBIC);
	//update 20181206 for the bug cvtColor
	cv::Mat temp1 = matDst1;
	cv::Mat temp2 = matDst2;
	cv::cvtColor(temp1, matDst1, cv::COLOR_BGR2GRAY);
	cv::cvtColor(temp2, matDst2, cv::COLOR_BGR2GRAY);

	int iAvg1 = 0, iAvg2 = 0;
	int arr1[64], arr2[64];

	for (int i = 0; i < 8; i++)
	{
		uchar* data1 = matDst1.ptr<uchar>(i);
		uchar* data2 = matDst2.ptr<uchar>(i);

		int tmp = i * 8;

		for (int j = 0; j < 8; j++)
		{
			int tmp1 = tmp + j;

			arr1[tmp1] = data1[j] / 4 * 4;
			arr2[tmp1] = data2[j] / 4 * 4;

			iAvg1 += arr1[tmp1];
			iAvg2 += arr2[tmp1];
		}
	}

	iAvg1 /= 64;
	iAvg2 /= 64;

	for (int i = 0; i < 64; i++)
	{
		arr1[i] = (arr1[i] >= iAvg1) ? 1 : 0;
		arr2[i] = (arr2[i] >= iAvg2) ? 1 : 0;
	}

	int iDiffNum = 0;

	for (int i = 0; i < 64; i++)
		if (arr1[i] != arr2[i])
			++iDiffNum;

	std::cout << "iDiffNum = " << iDiffNum << std::endl;

	if (iDiffNum <= 5)
		std::cout << "two images are very similar!" << std::endl;
	else if (iDiffNum > 10)
		std::cout << "they are two different images!" << std::endl;
	else
		std::cout << "two image are somewhat similar!" << std::endl;

	return iDiffNum;
}
